package com.skytech.component.monitor.enterprise_data_monitoring;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.FormateConnection;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class JianSheBingTuanService implements CrawlerScript {

    private static final Logger log = LoggerFactory.getLogger(JianSheBingTuanService.class);
    private static final String province = "建设兵团";

    @Autowired
    private ChromeBrowser chromeBrowser;
    @Autowired
    private SaveDataUtil saveDataUtil;

    @Override
    public void start() {
        for (int i = 1; i <= 3; i++) {
            String url = "http://220.171.32.30:8088/Default_eplist.aspx?xzqh=600000&qylx=" + i;

            Document document = null;
            try {
                document = FormateConnection.createConnection(Jsoup.connect(url))
                        .get();
                log.info("当前页面--{}", url);
            } catch (Exception e) {
                log.error(e.getMessage());
            }


            JSONArray jsonArray = JSONObject.parseObject(document.getElementsByTag("script").last().html().split("};")[0].substring(13) + "}").getJSONArray("localdata");
            ChromeDriver driver = chromeBrowser.getChromeDriver();
            for (Object o : jsonArray) {
                JSONObject json = JSONObject.parseObject(o.toString());
                String urlEnter = "http://220.171.32.30:8088/pub/pubepcom.aspx?Code=" + json.getString("Code");

                try {
                    driver.get(urlEnter);
                    log.info("当前页面--{}", driver.getCurrentUrl());
                    driver.findElementByXPath("//*[@id='jqxNavigationBar']/div[4]/a[1]").click();
                    Thread.sleep(3000);
                } catch (Exception e) {
                    log.error(e.getMessage());
                }
                driver.switchTo().frame("iframe_info");
                driver.findElementByXPath("//*[@id='dw_dm']").click();

                List<WebElement> webElementList = driver.findElementsByCssSelector("#dw_dm > option:nth-child(n+1)");

                for (int k = 0; k < webElementList.size(); k++) {
                    try {
                        webElementList.get(k).click();
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                    String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
                    Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
                    Elements allElements = parse.getAllElements();
                    String point = allElements.select("#dw_dm>option").get(k).text();

                    List<JSONObject> jsonObjectList = new ArrayList<>();
                    allElements.select("#tab_data > thead > tr:nth-child(1) >th:nth-child(n+2)").forEach(l -> {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("info", l.text());
                        jsonObjectList.add(jsonObject);

                    });
                    List<JSONObject> jsonObjects = new ArrayList<>();
                    if (point.contains("气")) {

                        for (int j = 0; j < jsonObjectList.size(); j++) {
                            int finalJ = j;
                            allElements.select("#tab_data > tbody tr").forEach(a -> {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("time", a.getElementsByTag("td").get(0).text());
                                jsonObject.put("info", jsonObjectList.get(finalJ).getString("info"));
                                jsonObject.put("value", a.getElementsByTag("td").get(3 * finalJ + 1).text());
                                jsonObjects.add(jsonObject);
                            });
                        }
                    } else {

                        for (int j = 0; j < jsonObjectList.size(); j++) {
                            int finalJ = j;
                            allElements.select("#tab_data > tbody tr").forEach(a -> {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("time", a.getElementsByTag("td").get(0).text());
                                jsonObject.put("info", jsonObjectList.get(finalJ).getString("info"));
                                jsonObject.put("value", a.getElementsByTag("td").get(2 * finalJ + 1).text());
                                jsonObjects.add(jsonObject);
                            });
                        }
                    }


                    List<MonitorData> monitorDataList = new ArrayList<>();
                    jsonObjects.forEach(l -> {
                        MonitorData monitorData = new MonitorData();
                        monitorData.setMonitorTime(l.getString("time"))
                                .setCompanyName(json.getString("Name"))
                                .setPollutionType(json.getString("qylx_name"))
                                .setAddress(json.getString("addr"))
                                .setIndustry(json.getString("hylx_name"))
                                .setMonitorInfo(l.getString("info"))
                                .setMonitorValue(l.getString("value"))
                                .setId(UUID.randomUUID().toString())
                                .setProvince(province)
                                .setMonitorPoint(point)
                                .setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        monitorDataList.add(monitorData);

                    });

                    saveDataUtil.saveTag(monitorDataList, province);
                }


            }
            driver.quit();
        }
    }

}
